import React, { useEffect, useState } from 'react';
import {
  Input,
  Form,
  Row,
  Col,
  Button,
  Table,
  Divider,
  Popconfirm,
  message,
  Select,
  Modal,
  Upload,
  Alert,
  Typography,
} from 'antd';
import { connect, useDispatch } from 'umi';
import PageTopFormContent from '@/components/PageTopFormContent';
import PaginationCommon from '@/components/PaginationCommon';
import StaffManageAddEdit from './components/staffEdit';
import OrgTreeSelect from '@/components/OrgTreeSelect';
import styles from './StaffManage.less';

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const { Option } = Select;
const { confirm } = Modal;
const { Text } = Typography;

const StaffManage = (props) => {
  const {
    stuffManageModel,
    loading: { effects },
  } = props;
  const { stuffList, stuffTotal } = stuffManageModel;
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const [currentPageNum, setCurrentPageNum] = useState(1);
  const [currentPageSize, setCurrentPageSize] = useState(10);
  const [fileUploading, setFileUploading] = useState(false);
  const [formData, setFormData] = useState({});
  const [drawerType, setDrawerType] = useState('add');
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [orgIdList, setOrgIdList] = useState([]);
  const [position, setPosition] = useState([]);
  const [editData, setEditData] = useState({});
  const [lookDisabled, setLookDisabled] = useState(false);
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const isDeleteList = [
    {
      value: '',
      label: '全部'
    },
    {
      value: 'Y',
      label: '已删除'
    },
    {
      value: 'N',
      label: '未删除'
    }
  ];

  const handleShowDrawer = (type, record) => {
    setDrawerVisible(true);
    setDrawerType(type);
    if (type === 'edit') {
      setEditData(record);
    } else if (type === 'look') {
      setEditData(record);
      setLookDisabled(true);
    }
  };

  const getStuffListData = () => {
    const { positionIdList, employeeId, employeeCode, employeeName, isDeleted } = formData;
    const positionId = positionIdList ? [Number(positionIdList)] : undefined;
    const submitData = {
      pageIndex: currentPageNum,
      pageSize: currentPageSize,
      positionIdList: positionId,
      employeeId,
      employeeCode,
      employeeName,
      orgIdList,
      isDeleted,
    };
    dispatch({
      type: 'stuffManageModel/getStuffList',
      payload: submitData,
    });
  };

  useEffect(() => {
    getStuffListData();
  }, [currentPageNum, currentPageSize, formData]);

  const handleSearch = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      // console.log(values);
      const param = { ...values };
      setFormData(param);
      setCurrentPageNum(1);
      resetSelection();
    });
  };

  const handleCloseDrawer = (update = false) => {
    setDrawerVisible(false);
    setEditData({});
    setLookDisabled(false);
    if (update) {
      handleSearch();
    }
  };

  const handleReset = () => {
    form.resetFields();
    setCurrentPageNum(1);
    setFormData({});
    setOrgIdList();
  };

  // 复效员工信息
  const handleRecovery = (ids) => {
    dispatch({
      type: 'stuffManageModel/revalidateSysEmployee',
      payload: ids,
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        message.success('复效成功');
        handleSearch();
      } else {
        message.error(errMsg);
      }
    });
  };

  // 删除员工信息
  const handleDelete = (ids) => {
    dispatch({
      type: 'stuffManageModel/deleteStuff',
      payload: ids,
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        message.success('删除成功');
        handleSearch();
      } else {
        message.error(errMsg);
      }
    });
  };

  const handlePaginationChange = (page, pageSize) => {
    setCurrentPageNum(page);
    setCurrentPageSize(pageSize);
  };

  const onSelect = (selectedKeysValue, info) => {
    setOrgIdList([info.value]);
    form.setFieldsValue({ positionIdList: undefined });
    dispatch({
      type: 'stuffManageModel/searchPosition',
      payload: { orgId: info.value },
    }).then((res) => {
      const { code, data, message } = res;
      if (code === 0) {
        setPosition(data);
      } else {
        message.error(message);
      }
    });
  };

  const onOrgListChange = (selectKey) => {
    setOrgIdList(selectKey);
    if (!selectKey) {
      setPosition([]);
      form.setFieldsValue({ positionIdList: undefined });
    }
  };

  const handleBatchDel = () => {
    if (selectedRows.length > 0) {
      const stuffNameList = [];
      const stuffIdList = [];
      selectedRows.forEach((item) => {
        stuffNameList.push(item.employeeName);
        stuffIdList.push(item.id);
      });
      confirm({
        title: `确定要批量删除：${
          stuffNameList.length > 3
            ? `${stuffNameList.slice(0, 3).join('、')}等`
            : stuffNameList.join('、')
        }员工吗？`,
        onOk() {
          handleDelete(stuffIdList);
        },
      });
    } else {
      message.warn('请选择要删除的角色');
    }
  };
  const columns = [
    {
      title: '员工 ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '工号',
      dataIndex: 'employeeCode',
      key: 'employeeCode',
    },
    {
      title: '姓名',
      dataIndex: 'employeeName',
      key: 'employeeName',
    },
    {
      title: '公司',
      dataIndex: 'companyName',
      key: 'companyName',
      ellipsis: {
        showTitle: false,
      },
      render: (val) =>
        val ? (
          <Text style={{ width: 120 }} ellipsis={{ tooltip: val }}>
            {val}
          </Text>
        ) : (
          '-'
        ),
    },
    {
      title: '组织',
      dataIndex: 'orgName',
      key: 'orgName',
      ellipsis: {
        showTitle: false,
      },
      render: (val, record) => {
        const text = record.orgList.map((item) => item.orgName).join('、');
        return (
          <Text style={{ width: 120 }} ellipsis={{ tooltip: text }}>
            {text}
          </Text>
        );
      },
    },
    {
      title: '岗位',
      dataIndex: 'positionName',
      key: 'positionName',
      ellipsis: {
        showTitle: false,
      },
      render: (val, record) => {
        const text = record.positionList.map((item) => item.positionName).join('、');
        return (
          <Text style={{ width: 120 }} ellipsis={{ tooltip: text }}>
            {text}
          </Text>
        );
      },
    },
    {
      title: '是否删除',
      dataIndex: 'isDeleted',
      key: 'isDeleted',
      render: (text) => (
        <span>{text === 'Y' ? '已删除' : '未删除'}</span>
      ),
    },
    {
      title: '联系方式',
      dataIndex: 'mobilePhone',
      key: 'mobilePhone',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (text, record) => (
        <div>
          {record.isDeleted === 'Y' ? (
            <Popconfirm
              title="你确定要复效该员工信息吗?"
              onConfirm={() => handleRecovery([record.id])}
            >
              <Button type="link">复效</Button>
            </Popconfirm>
          ) : (
            <Popconfirm title="你确定要删除该员工信息吗?" onConfirm={() => handleDelete([record.id])}>
              <Button type="link">删除</Button>
            </Popconfirm>
          )}
          <Divider type="vertical" />
          <Button type="link" onClick={() => handleShowDrawer('look', record)}>详情</Button>
          <Divider type="vertical" />
          <Button type="link" onClick={() => handleShowDrawer('edit', record)} disabled={record.isDeleted === 'Y'}>修改</Button>
        </div>
      ),
    },
  ];
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeysParam, selectedRowsParam) => {
      setSelectedRowKeys(selectedRowKeysParam);
      setSelectedRows(selectedRowsParam);
    },
  };

  const resetSelection = () => {
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };
  return (
    <div className={styles.root}>
      <PageTopFormContent
        title="员工管理"
        content={
          <Form {...layout} form={form} name="advanced_search">
            <Row gutter={[32, 16]}>
              <Col className="gutter-row" span={6}>
                <Form.Item name="employeeId" label="员工ID">
                  <Input placeholder="请输入员工ID" />
                </Form.Item>
              </Col>
              <Col className="gutter-row" span={6}>
                <Form.Item name="employeeCode" label="工号">
                  <Input placeholder="请输入工号" />
                </Form.Item>
              </Col>
              <Col className="gutter-row" span={6}>
                <Form.Item name="employeeName" label="姓名">
                  <Input placeholder="请输入姓名" />
                </Form.Item>
              </Col>
              <Col className="gutter-row" span={6}>
                <Form.Item name="orgIdList" label="组织">
                  <OrgTreeSelect
                    // checkable={true}
                    onSelect={onSelect}
                    onChange={onOrgListChange}
                    placeholder="请选择"
                    dropdownMatchSelectWidth={false}
                    dropdownStyle={{ maxWidth: 400 }}
                    allowClear
                  />
                </Form.Item>
              </Col>
              <Col className="gutter-row" span={6}>
                <Form.Item name="positionIdList" label="岗位">
                  <Select placeholder="请选择">
                    {position.length > 0
                      ? position.map((item) => <Option key={item.id}>{item.name}</Option>)
                      : null}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="isDeleted" label="是否删除">
                  <Select placeholder="请选择">
                    {isDeleteList.map((item, index) => (
                      <Option key={index} value={item.value}>
                        {item.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12} style={{ textAlign: 'right' }}>
                <Form.Item wrapperCol={{ span: 24 }}>
                  <Button type="primary" onClick={handleSearch}>
                    查询
                  </Button>
                  <Button style={{ marginLeft: 16 }} onClick={handleReset}>
                    重置
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        }
      />
      <div className={styles.tableWapper}>
        <div className={styles.listHead}>
          <div className={styles.listTitle}>员工列表</div>
          <div className={styles.btnGroup}>
            {selectedRowKeys.length !== 0 && (
              <Alert
                type="info"
                message={
                  <>
                    已选中 <strong>{selectedRowKeys.length}</strong> 条数据
                    <Button
                      type="link"
                      size="small"
                      onClick={() => {
                        resetSelection();
                      }}
                    >
                      清空
                    </Button>
                  </>
                }
                style={{ display: 'inline-block', padding: '3px 6px' }}
              />
            )}
            <Button
              type="link"
              onClick={() => {
                window.open(
                  `${location.origin}/usercenter-admin-web/Template-SysEmployee.xlsx`,
                  '_blank',
                );
              }}
            >
              下载导入模板
            </Button>
            <Upload
              showUploadList={false}
              name="file"
              action="/usercenter-admin-app/admin/sysEmployee/import"
              onChange={(e) => {
                const { status, response } = e.file;
                if (status === 'uploading') {
                  setFileUploading(true);
                } else if (status === 'done') {
                  // 如果上传返回有错误，则提示错误信息，重置 loading 状态
                  if (response && response.code !== 0) {
                    message.error(response?.message || '导入失败');
                  } else {
                    message.success(response?.data || '导入成功');
                    handleReset();
                    getStuffListData();
                  }
                  setFileUploading(false);
                }
              }}
            >
              <Button className={styles.marginLeft} loading={fileUploading}>
                批量导入
              </Button>
            </Upload>
            <Button
              className={styles.marginLeft}
              onClick={handleBatchDel}
              type="danger"
              disabled={selectedRows.length === 0}
            >
              批量删除
            </Button>
            <Button
              type="primary"
              className={styles.marginLeft}
              onClick={() => handleShowDrawer('add')}
            >
              新增
            </Button>
          </div>
        </div>
        <div className={styles.listTable}>
          <Table
            rowKey="id"
            rowSelection={{
              ...rowSelection,
            }}
            columns={columns}
            dataSource={stuffList}
            pagination={false}
            scroll={{ x: 'max-content' }}
            loading={effects['stuffManageModel/getStuffList']}
          />
          <PaginationCommon
            style={{ textAlign: 'right' }}
            total={stuffTotal}
            onChange={handlePaginationChange}
            current={currentPageNum}
            pageSize={currentPageSize}
          />
        </div>
      </div>
      {drawerVisible && (
        <StaffManageAddEdit
          drawerType={drawerType}
          lookDisabled={lookDisabled}
          editData={editData}
          handleCloseDrawer={handleCloseDrawer}
        />
      )}
    </div>
  );
};
export default connect((state) => state)(StaffManage);
